package com.kuang.listener;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class OnlineListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        ServletContext servletContext = httpSessionEvent.getSession().getServletContext();
        System.out.println(httpSessionEvent.getSession().getId());
        Integer onlineCount = (Integer) servletContext.getAttribute("OnlineCount");
        if(onlineCount==null){
//            onlineCount+=1;
            onlineCount=new Integer(1);
        }else{
         int count = onlineCount.intValue();
         onlineCount=new Integer(count+1);
//        等价于下面语句：
//         onlineCount=new Integer(count++);
        }
        servletContext.setAttribute("OnlineCount",onlineCount);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        ServletContext servletContext = httpSessionEvent.getSession().getServletContext();
//        httpSessionEvent.getSession().invalidate();
        Integer onlineCount = (Integer) servletContext.getAttribute("OnlineCount");

        if(onlineCount==null){
            onlineCount=new Integer(0);

        }else {
            int count=onlineCount.intValue();
            onlineCount=new Integer(count-1);
        }
        servletContext.setAttribute("OnlineCount",onlineCount);
    }
}
